package com.kkb.robotcustomerservice.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.kkb.robotcustomerservice.entities.KnowledgeBase;
import com.kkb.robotcustomerservice.service.impl.KnowledgeBaseServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
/**
 * 读取表监听器
 * */
public class ExcelListener extends AnalysisEventListener<KnowledgeBase> {
    //每隔3000条存储数据库然后清理list ，方便内存回收
    private static final int BATCH_COUNT = 3000;
    List<KnowledgeBase> list = new ArrayList<KnowledgeBase>();
    private KnowledgeBaseServiceImpl knowledgeBaseService;
    private User user;

    public ExcelListener(KnowledgeBaseServiceImpl knowledgeBaseService,User user) {
        this.knowledgeBaseService = knowledgeBaseService;
        this.user = user;
    }


    @Override
    public void invoke(KnowledgeBase knowledgeBase, AnalysisContext analysisContext) {
        list.add(knowledgeBase);
        //如果达到BATCH_COUNT值存储数据库，防止OOM
        if (list.size()>=BATCH_COUNT){
            saveDate();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveDate();
    }

    private void saveDate(){
        knowledgeBaseService.insertList(list,user);
    }
}
